using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using DreamHome.Models;

var builder = WebApplication.CreateBuilder(args);

#region Config Pre-modify
builder.Configuration["StoredFilesPath"] = (builder.Configuration["StoredFilesPath"].StartsWith('.')) ? 
    builder.Configuration["StoredFilesPath"] : 
    Path.Combine(builder.Environment.WebRootPath, builder.Configuration["StoredFilesPath"]);
builder.Configuration["StoredTempFilesPath"] = (builder.Configuration["StoredTempFilesPath"].StartsWith('.')) ?
    builder.Configuration["StoredFilesPath"] : 
    Path.Combine(builder.Environment.WebRootPath, builder.Configuration["StoredTempFilesPath"]);
builder.Configuration["DatabasePath"] = (builder.Configuration["DatabasePath"].StartsWith('.')) ? 
    builder.Configuration["DatabasePath"] : 
    Path.Combine(builder.Environment.WebRootPath, builder.Configuration["DatabasePath"]);
if(!Directory.Exists(builder.Configuration["StoredFilesPath"]))
    Directory.CreateDirectory(builder.Configuration["StoredFilesPath"]);
if(!Directory.Exists("StoredTempFilesPath"))
    Directory.CreateDirectory("StoredTempFilesPath");
if(File.Exists(builder.Configuration["DatabasePath"]))
    builder.Configuration["DatabasePath"] = "Data Source=" + builder.Configuration["DatabasePath"];
else
    throw new InvalidProgramException("Invalid dadabase path!");
#endregion

// Add services to the container.
builder.Services.AddRazorPages();

/*
builder.Services.AddDbContext<UserInfoContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("UserInfoContext") ?? throw new InvalidOperationException("Connection string 'UserInfoContext' not found.")));
*/
builder.Services.AddDbContext<UserInfoContext>(options =>
    options.UseSqlite(builder.Configuration["DatabasePath"] ?? throw new InvalidOperationException("Connection string 'UserInfoContext' not found.")));


var app = builder.Build();

#region Seed Data
/*
using(var scope = app.Services.CreateScope())
using(var context = new UserInfoContext(
    scope.ServiceProvider.GetRequiredService<DbContextOptions<UserInfoContext>>()
))
{
    context.UserInfo?.AddRange(
        new UserInfo
        {
            ID = 0,
            Name = "David",
            Key = "123456",
            Quote = "Shit you, bugs!",
            LastLogin = DateTime.Now
        }
    );
    context.SaveChanges();
}
*/
#endregion

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
